#!/usr/bin/env python

import sys
import re
from datetime import datetime

TASKS = 0
ISRS = 1
AGENTS = 8

QUEUES = 3
EVENTS = 4
NOTES  = 7



tasksnames = []
queuesnames = []
eventsnames = []
notesnames = []

offset_nsec = 0
first_tstamp = 0

nams = []  # tdifilename  + ' ' + 0 / 3 / 4 / 7 + ' ' + 0.. / 3000.. / 4000.. / 7000..
evts = []  # epoch-tstamp + ' ' + 0 / 3 / 4 / 7 + ' ' + thenam + ' ' + 'OCC/STA/STO/' + ' ' + 0.. / 3000.. / 4000.. / 7000.. + ' ' + descr


def build(tdifilename):

   global nams
   global evts
   global offset_nsec
   global first_tstamp

   f = open(tdifilename)

   for line in f:
      if line.startswith('END'):
         offset_nsec = int(line.split()[1])

   f.seek(0)

   for line in f:

      if line.startswith('NAM'):

         namwords = line.split()

         nams.append(tdifilename + ' ' + namwords[2] + ' ' + namwords[3])


      if line.startswith('OCC'):

         occwords = line.split()

         tstamp = int(occwords[3])

         if first_tstamp == 0:
            first_tstamp = tstamp

         dscwords = f.next().split()

         for nam in nams:
            namwords = nam.split()

            if namwords[0] == tdifilename:

               if occwords[2] == namwords[1]:

                  thenam = namwords[2]

         evts.append(str(offset_nsec + tstamp) + ' ' + occwords[1] + ' ' + 'OCC' + ' ' +  thenam + ' ' + dscwords[3])


      if line.startswith('STA'):

         stawords = line.split()

         tstamp = int(stawords[3])

         if first_tstamp == 0:
            first_tstamp = tstamp


         if int(stawords[1]) == TASKS or int(stawords[1]) == ISRS or int(stawords[1]) == AGENTS: # @T+ / @A+ / @I+ STA DSC

            dscwords = f.next().split()

            for nam in nams:
               namwords = nam.split()

               if namwords[0] == tdifilename:

                  if stawords[2] == namwords[1]:

                     thenam = namwords[2]

            evts.append(str(offset_nsec + tstamp) + ' ' + stawords[1] + ' ' + 'STA' + ' ' + thenam + ' ' + dscwords[3])


         if int(stawords[1]) == EVENTS: # @E+  STA STO DSC

            stowords = f.next().split()

            dscwords = f.next().split()

            for nam in nams:
               namwords = nam.split()

               if namwords[0] == tdifilename:

                  if stawords[2] == namwords[1]:

                     thenam = namwords[2]

            evts.append(str(offset_nsec + tstamp) + ' ' + stawords[1] + ' ' + 'STASTO' + ' ' + thenam + ' ' + dscwords[3])


         if int(stawords[1]) == QUEUES: # ~ STA / STO

            for nam in nams:
               namwords = nam.split()
            
               if namwords[0] == tdifilename:
            
                  if stawords[2] == namwords[1]:
            
                     thenam = namwords[2]

            evts.append(str(offset_nsec + tstamp) + ' ' + stawords[1] + ' ' + stawords[0] + ' ' + thenam + ' ' + stawords[4])



      if line.startswith('STO'):

         stowords = line.split()

         tstamp = int(stowords[3])

         if first_tstamp == 0:
            first_tstamp = tstamp


         if int(stowords[1]) == TASKS or int(stowords[1]) == ISRS or int(stowords[1]) == AGENTS: # @T+ / @I+ / @A+ STO DSC

            dscwords = f.next().split()

            for nam in nams:
               namwords = nam.split()

               if namwords[0] == tdifilename:

                  if stowords[2] == namwords[1]:

                     thenam = namwords[2]

            evts.append(str(offset_nsec + tstamp) + ' ' + stowords[1] + ' ' + 'STO' + ' ' + thenam + ' ' + dscwords[3])


         if int(stowords[1]) == QUEUES: # ~ STA / STO

            for nam in nams:
               namwords = nam.split()

               if namwords[0] == tdifilename:

                  if stowords[2] == namwords[1]:
            
                     thenam = namwords[2]
            
            evts.append(str(offset_nsec + tstamp) + ' ' + stowords[1] + ' ' + stowords[0] + ' ' + thenam + ' ' + stowords[4])


   #for evt in evts:
   #   sys.stderr.write(evt[:120] + '\n')

   f.close()


def print_result(curr_evtwords):
   i = 0;
   for item in curr_evtwords:
      if i % 2:
         print ",",item,',',
      else:
         print "\"%s\"" %item,

      i+= 1
   print


def main():

   global offset_nsec
   global first_tstamp

   if len(sys.argv) >= 4:

      build(sys.argv[1])

      offset_nsec += first_tstamp;

      matches = []
      progs = []
      for match in sys.argv[2:]:
         matches.append(match) 

      curr_evtwords = []

      state = 'MATCH_FIRST'
      last_match = 0;

      for evt in evts:

         #sys.stderr.write(evt[:130] + '\n')

         #1438899095850210044 0 STA [mwserver][1711][0]poll() [mwserver][1711][0]poll(),7f4090,2

         evtwords = evt.split()

         if state == 'MATCH_FIRST':

            if (re.compile(matches[0]).findall(evtwords[4]) and (evtwords[2] == 'STA' or evtwords[2] == 'OCC' or evtwords[2] == 'STASTO')):

               #print 'MATCH_FIRST match first', evtwords[0], evtwords[4], offset_nsec

               curr_evtwords.append(re.compile(matches[0]).search(evtwords[4]).group(0))
               curr_evtwords.append("%08.3f" % (round((int(evtwords[0]) - offset_nsec) / 1000000000.0, 3)))
               tstamp_begin = int(evtwords[0])
               last_match = 0;
               state = 'MATCH_NEXT'

         elif state == 'MATCH_NEXT':

            if (re.compile(matches[last_match]).search(evtwords[4]) and (evtwords[2] == 'STA' or evtwords[2] == 'OCC' or evtwords[2] == 'STASTO')):

               #print 'MATCH_NEXT match again', evtwords[0], evtwords[4]

               curr_evtwords.append(re.compile(matches[last_match]).search(evtwords[4]).group(0))
               curr_evtwords.append("%06.3f" % (round((int(evtwords[0]) - tstamp_begin) / 1000000000.0, 3)))

            elif (re.compile(matches[last_match + 1]).search(evtwords[4]) and (evtwords[2] == 'STA' or evtwords[2] == 'OCC' or evtwords[2] == 'STASTO')):

               #print 'MATCH_NEXT match next', last_match, len(matches), evtwords[0], evtwords[4]

               curr_evtwords.append(re.compile(matches[last_match + 1]).search(evtwords[4]).group(0))
               curr_evtwords.append("%06.3f" % (round((int(evtwords[0]) - tstamp_begin) / 1000000000.0, 3)))
               tstamp_end = int(evtwords[0])
               last_match += 1
               if last_match + 1 == len(matches):
                  state = 'MATCH_FINAL'

            else:

               for i in range(last_match + 2, len(matches)):

                  if (re.compile(matches[i]).search(evtwords[4]) and (evtwords[2] == 'STA' or evtwords[2] == 'OCC' or evtwords[2] == 'STASTO')):

                     #print 'MATCH_NEXT bad match', evtwords[0], evtwords[4]
                     
                     curr_evtwords = []
                     state = 'MATCH_FIRST'
                     break


         elif state == 'MATCH_FINAL':

            # if we find the first again we are done
            if (re.compile(matches[0]).search(evtwords[4]) and (evtwords[2] == 'STA' or evtwords[2] == 'OCC' or evtwords[2] == 'STASTO')):

               #print 'MATCH_FINAL match first', last_match, len(matches), evtwords[0], evtwords[4]
               delta = tstamp_end - tstamp_begin

               print_result(curr_evtwords)

               #i = 0;
               #for item in curr_evtwords:
               #   if i % 2:
               #      print '@',item,
               #   else:
               #      print '"', item, '"',
               #
               #   i+= 1


               curr_evtwords = []
               curr_evtwords.append(re.compile(matches[0]).search(evtwords[4]).group(0))
               curr_evtwords.append("%08.3f" % (round((int(evtwords[0]) - offset_nsec) / 1000000000.0, 3)))
               tstamp_begin = int(evtwords[0])

               last_match = 0;
               state = 'MATCH_NEXT'

            # if we find the last again
            elif (re.compile(matches[last_match]).search(evtwords[4]) and (evtwords[2] == 'STA' or evtwords[2] == 'OCC' or evtwords[2] == 'STASTO')):

               #print 'MATCH_FINAL match again', last_match, len(matches), '<', evtwords[0], evtwords[4]

               tstamp_end = int(evtwords[0])
               curr_evtwords.append(re.compile(matches[last_match]).search(evtwords[4]).group(0))
               curr_evtwords.append("%06.3f" % (round((int(evtwords[0]) - tstamp_begin) / 1000000000.0, 3)))

      # print final one
      print_result(curr_evtwords)

   else:

      print("Usage: %s tdifile pattern1 pattern2 [pattern3]..." % sys.argv[0])


if __name__ == "__main__":
   main()
